package main.Communication;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import main.Communication.Interface.ClientInterface;

/**
 * 客户端类
 * @author svitter
 *
 */

public class Client implements ClientInterface{
	private static int 			PORT    	=   8888;
	private Socket 				socket      =   null;
	private ObjectOutputStream 	dos  		=   null;
	private ObjectInputStream 	dis   		=   null;
	private String 				ip			=   "127.0.0.1";        // 要链接的ip
	private recvThread 			recv 		= 	null;				// 线程类
	private boolean 			bConnected 	= 	false; 				// 判断该客户端是否链接
    private Thread              getInfor;
    
    public Client() {
    	recv = new recvThread();
		connect(this.ip);
		this.getInfor = new Thread(recv);
        getInfor.start();
    }

    public Client(String ip) {
    	this.ip = ip;
		connect(this.ip);
		this.getInfor   = new Thread(recv);
        getInfor.start();
    }

	public Client(String ip, recvThread recv) {
		// 可以考虑从本机多个游戏
		this.recv 		= recv;
		this.ip         = ip;
		connect(this.ip);
		this.getInfor   = new Thread(recv);
        getInfor.start();
	}
	
	public boolean getConncet() {
		return this.bConnected;
	}
    
	/**
	 * 建立链接
	 * @param ip
	 */
	public void connect(String ip) {
		try {
            System.out.println("[Client]: join ip is: " + ip + "@" + PORT);
			socket 		= new Socket(ip, PORT); // 建立客户端对象
			dos 		= new ObjectOutputStream(socket.getOutputStream());
			dis 		= new ObjectInputStream(socket.getInputStream());

			recv.setDis(dis);

			bConnected 	= true;
			recv.setConnect(bConnected);

		} catch (UnknownHostException e) {
			e.printStackTrace();
            System.out.println("[Client]: Unknow Host");
		} catch (IOException e) {
            System.out.println("[Client]: IOException");
			e.printStackTrace();
		}
	}

	/**
	 * 关闭客户端
     * @
	 */
	public void disconnect() {
		try {
			// 退出时发送讯号
            System.out.println("[Client]: disconnect.");
            
			dos.close();
			dis.close();
			socket.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

        // 似乎有些问题
		try { 
			// dos.writeObject(str);
			dos.flush();
			// dos.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	/**
	 * 发送数据
	 * @param mes
	 */
	public void send(Object mes) {
		try {
			dos.writeObject(mes);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
